#!/bin/bash
 #Author: congyang
 #Time:2020-07-15 21:55:58
 #Version: V2.0
 #Description: This is a script to install nginx , you only need to change some of these parameters

. /etc/init.d/functions


case $1 in 
"-v")
if [ $# -eq 4 ]; then
    INPUT_VERSION=$2
    INPUT_PATH=$4
else
    echo $"Usage: sh $0 [ -h|--help ]" >&2
    exit 1
fi
;;
"-h"|"--help")
echo $"Usage: sh $0 [-v] [-d]" >&2
echo $"  E.g: sh $0 -v 2.3.2 -d /opt/platform/nginx" >&2
exit 1
;;
*)
echo $"Usage: sh $0 [ -h|--help ]" >&2
exit 1
;;
esac

LOGFILE=/tmp/nginx.log


# Select nginx version, like '2.3.2'
PACKAGE_NAME=tengine-${INPUT_VERSION}.tar.gz
APP_NAME=tengine-${INPUT_VERSION}
FULL_URL_PATH=http://tengine.taobao.org/download/${PACKAGE_NAME}


# Input installation directory, like '/opt/platform/nginx'
DESTPATH=${INPUT_PATH}


function CheckEnv()
{
    # check user
    if [ `id -u` != 0 ]; then
        echo -e "\033[43;30mPermission Denied, Use root.\033[0m"  | tee ${LOGFILE}
        exit 1
    fi

    # check lib
    yum provides '*/applydeltarpm'
    installs=( deltarpm gcc gcc-c++  zlib zlib-devel pcre-devel openssl openssl-devel )
    for ((i=0; i<${#installs[@]}; i++))
    do
        yum install ${installs[i]} -y | tee ${LOGFILE}
        if [ "$?" == "0" ]; then
            action "${installs[i]} install successful" /bin/true | tee ${LOGFILE}
        else
            action "${installs[i]} install failed" /bin/false | tee ${LOGFILE}
            exit 1
        fi
    done

    # check process
    NG=$(ps -C nginx -o pid |wc -l) 
    if [ ${NG} -gt "1" ]; then
        echo -e "\033[43;30mNginx is running, Can't install\033[0m" | tee ${LOGFILE}
        exit 1
    fi

    # check nginx file
    rpm -qa | grep nginx
    if [ $? -eq 0 ]; then
        echo -e "\033[43;30mexist nginx file\033[0m" | tee ${LOGFILE}
        exit 1
    fi
}

function DownloadInstall()
{
    # download
    if [ ! -f /tmp/${PACKAGE_NAME} ]; then
        wget -c -O /tmp/${PACKAGE_NAME} ${FULL_URL_PATH}  | tee ${LOGFILE}
        if [ "$?" == 0 ]; then
            # unarchive
            tar -zxvf /tmp/${PACKAGE_NAME} -C /tmp/ | tee ${LOGFILE}
            if [ "$?" == 0 ]; then
                # install
                cd /tmp/${APP_NAME} && /bin/sh ./configure --prefix=${DESTPATH} && make && make install | tee ${LOGFILE}
                if [ "$?" == 0 ]; then
                    action "${APP_NAME} install Successful" /bin/true | tee ${LOGFILE}
                else
                    action "${APP_NAME} install Failed, Please Check!!!" /bin/false | tee ${LOGFILE}
                    exit 1
                fi
            fi
        fi
    else
        # unarchive
        tar -zxvf /tmp/${PACKAGE_NAME} -C /tmp/ | tee ${LOGFILE}
        if [ "$?" == 0 ]; then
            # install
            cd /tmp/${APP_NAME} && /bin/sh ./configure --prefix=${DESTPATH} && make && make install | tee ${LOGFILE}
            if [ "$?" == 0 ]; then
                action "${APP_NAME} install Successful" /bin/true | tee ${LOGFILE}
            else
                action "${APP_NAME} install Failed, Please Check!!!" /bin/false | tee ${LOGFILE}
                exit 1
            fi
        fi
	fi
}


function SelfStarting ()
{
    #check kernel release
    kernel=`uname -r | awk -F '.' '{print $4}'`
    if [ $kernel == 'el6' ]; then
        cat >/etc/init.d/nginx<<EOF
#!/bin/bash
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /etc/nginx/nginx.conf
# config: /etc/sysconfig/nginx
# pidfile: /var/run/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "\$NETWORKING" = "no" ] && exit 0
NGINX_HOME="${DESTPATH}/"
nginx=\$NGINX_HOME"sbin/nginx"
prog=\$(basename \$nginx)
NGINX_CONF_FILE=\$NGINX_HOME"conf/nginx.conf"
[ -f /etc/sysconfig/nginx ] && /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
start() {
    [ -x \$nginx ] || exit 5
    [ -f \$NGINX_CONF_FILE ] || exit 6
    echo -n \$"Starting \$prog: "
    daemon \$nginx -c \$NGINX_CONF_FILE
    retval=\$?
    echo
    [ \$retval -eq 0 ] && touch \$lockfile
    return \$retval
}
stop() {
    echo -n \$"Stopping \$prog: "
    killproc \$prog -QUIT
    retval=\$?
    echo
    [ \$retval -eq 0 ] && rm -f \$lockfile
    return \$retval
    killall -9 nginx
}
restart() {
    configtest || return \$?
    stop
    sleep 1
    start
}
reload() {
    configtest || return \$?
    echo -n \$"Reloading \$prog: "
    killproc \$nginx -HUP
    RETVAL=\$?
    echo
}
force_reload() {
    restart
}
configtest() {
    \$nginx -t -c \$NGINX_CONF_FILE
}
rh_status() {
    status \$prog
}
rh_status_q() {
    rh_status >/dev/null 2>&1
}
case "\$1" in
start)
    rh_status_q && exit 0
    \$1
;;
stop)
    rh_status_q || exit 0
    \$1
;;
restart|configtest)
    \$1
;;
reload)
    rh_status_q || exit 7
        \$1
;;
force-reload)
    force_reload
;;
status)
    rh_status
;;
condrestart|try-restart)
    rh_status_q || exit 0
;;
*)
echo \$"Usage: \$0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|test}"
exit 2
esac
EOF
        /bin/chmod u+x /etc/init.d/nginx && /sbin/chkconfig --add nginx && /sbin/chkconfig nginx on && /sbin/chkconfig --list | grep nginx | tee ${LOGFILE}
        if [ "$?" == 0 ]
        then
            echo "Self-starting has been added..." | tee ${LOGFILE}
            echo "you can execution to start NGINX ==> service nginx start" | tee ${LOGFILE}
            echo "if you want to open the filewall,you can add this rule:" | tee ${LOGFILE}
            echo "-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT" | tee ${LOGFILE}
        else
            echo "Self-startup failed..." | tee ${LOGFILE}
            exit 1
        fi
    elif [ $kernel == 'el7' ]; then
        cat >/usr/lib/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStartPre=${DESTPATH}/sbin/nginx -t
ExecStart=${DESTPATH}/sbin/nginx
ExecStop=${DESTPATH}/sbin/nginx -s stop
ExecReload=${DESTPATH}/sbin/nginx -s reload
KillMode=process
Restart=on-failure
RestartSec=30s
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
        systemctl daemon-reload && systemctl enable nginx.service && systemctl start nginx.service | tee ${LOGFILE}
        if [ "$?" == 0 ]
        then
            echo "Self-starting has been added and running..." | tee ${LOGFILE}
            echo "You can use the following command to control nginx service" | tee ${LOGFILE}
            echo "systemctl start/stop/reload/status nginx.service" | tee ${LOGFILE}
        else
            echo "Self-startup failed..." | tee ${LOGFILE}
            exit 1
        fi
    else
        action "Temporarily does not support other operating systems!" /bin/false | tee ${LOGFILE}
    fi
}
    



function main()
{
CheckEnv
DownloadInstall
SelfStarting
}

main